package de.wefunkdroid.core;

import android.media.MediaPlayer;
import android.util.Log;
import java.io.IOException;

public class Streamplayer {
	String url;
	MediaPlayer mp;
	boolean playing;

	public Streamplayer() {
		mp = new MediaPlayer();
	}

	public Streamplayer(String url) {
		mp = new MediaPlayer();
	}

	public void prepareNewMedia(String url) {
		if (mp == null)
			mp = new MediaPlayer();
		if (playing) {
			mp.stop();
			mp.release();
			mp = new MediaPlayer();
			playing = !playing;
		}
		try {
			mp.setDataSource(url);
			mp.prepare();
		} catch (IllegalArgumentException e) {
			Log.e("IllegalArgumentException", "Error", e);
		} catch (IllegalStateException e) {
			Log.e("IllegalStateException", "Error", e);
		} catch (IOException e) {
			Log.e("IOException", "Error", e);
		}
	}

	public void startPlayer() {
		if (mp == null) {
			return;
		} else {
			mp.start();
			playing = true;
			return;
		}
	}

	public void stopPlayer() {
		if (mp == null) {
			return;
		} else {
			mp.stop();
			playing = false;
			return;
		}
	}

	public void killPlayer() {
		if (playing)
			stopPlayer();
		mp.release();
		mp = null;
		playing = false;
	}

	public void togglePause() {
		if (playing) {
			try {
				mp.pause();
			} catch (Exception e) {
				Log.e("IllegalStateException", e.getCause().toString());
			}
			playing = false;
		} else {
			try {
				mp.start();
			} catch (Exception e) {
				Log.e("IllegalStateException", e.getCause().toString());
			}
			playing = true;
		}
	}

	public void seek(int mspos) {
		mp.seekTo(mspos);
	}

	public void toggleplay() {
		if (mp.isPlaying())
			mp.pause();
		else
			mp.start();
	}
}
